<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;

use app\Common;
use app\controller\Token;
use app\model\UserModel;
use app\model\DeptModel;


class Acc{
    //常用数据表内容 及常用字典
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";
    var $dept=[];
    var $users =[];
    var $payment =[];

    var $status=array('1'=>'待审核','2'=>'已审核','4'=>'已取消');
    var $acc_type=array(1=>'学费(收款)',2=>'补考费(收款)',3=>'普通收款',4=>'红包',5=>'推广费',6=>'其他付款',7=>'提现');

    public function __construct(){

        $um=new UserModel();
        $this->users = $um->getAll();

        $dm=new DeptModel();
        $this->dept = $dm->getAll();

        $list = Db::table('sys')->where('id',1)->value('payment');
        $arr = explode(",",$list);
        foreach($arr as $payment){
            $aa = explode(":",$payment);
            $this->payment[$aa[0]]=$aa[1];
        }

    }

    public function getOne(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");  
        
        $all=Request::param();

        return json(['code'=>0,'msg'=>'没找到任何信息！']);

    }

     public function index(){

        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");

        $all=Request::param();

        return View::fetch();
    }  


    //充值，后台操作
    public function money_io($type='',$value=0,$all=[]){
        $uid=Session::get('logonid');
        $all = Request::param();

        if(empty($uid) && empty($all['token'])) return '非法操作,系统已记录来源!';

        //app端提交token
        if(!empty($all['token'])){
            $token =new token();
            $res = $token->check_token($all['token']);
            if($res['code']==0) return json($res);

            $all['cid'] = $res['customer']['id'];

        }else{
            //后台录入用session判断
            if(empty($uid)) return header("location:/index.php/login/index/target/admin");
        }

        if(!empty($all['money'])){

            if(empty($all['cid'])) return json(['code'=>0,'msg'=>'找不到客户 1!']);
            $cid = $all['cid'];

            $customer = Db::table('customer')->find($cid);
            if(!$customer) return json(['code'=>0,'msg'=>'找不到客户 2!']);

            if(!is_numeric($all['money'])){
                return json(['code'=>0,'msg'=>'金额错误!']);
            }
            if(empty($all['type'])) {
                return json(['code'=>0,'msg'=>'类型错误!']);
            }
            if(empty($all['payment'])) {
                return json(['code'=>0,'msg'=>'支付方式错误!']);
            }            
            
            //退款或提现(6,7)
            if($all['type']>5){
                if($all['money']<10) return json(['code'=>0,'msg'=>'金额低于10元就别提现了吧，不然财务人员很累的哦!']);
                $all['money'] = -$all['money'];
                $acc_list = Db::query('select * from acc_log where customer_id=? and type=7 and status=1',[$cid]);
                if(count($acc_list)) return json(['code'=>0,'msg'=>'提现或退款已在处理中，请耐心等待财务审核打款！']);                
            }            

            $acc_log=array(
                'type'=>$all['type'],
                'customer_id'=>$cid,
                'dept_id'=>$customer['dept_id'],
                'money'=>$all['money'],
                'memo'=>!empty($all['memo'])?$all['memo']:'',
                'payment'=>$all['payment'],
                'creater'=>!empty($all['token'])?2:$uid,
                'create_time'=>date('Y-m-d H:i:s'),
                'status'=>1
            );

            $nid =Db::table('acc_log')->insertGetId($acc_log);
            if(!empty($all['token']) && $nid){
                return json(['code'=>1,'msg'=>'提现已申请，待财务审核打款！']);
            }else{

                $row = Db::table('acc_log')->find($nid);
                $row['customer_id_name'] =Db::table('customer')->where('id',$row['customer_id'])->value('name');
                $row['type_name'] =$this->acc_type[$row['type']];
                $row['status_name'] =$this->status[$row['status']];
                $row['creater_name'] =$this->users[$row['creater']]['name'];
                $row['payment_name'] =$this->payment[$row['payment']];
                $row['money'] =number_format($row['money'],2);

                return json_encode(['code'=>1,'data'=>$row,'msg'=>'操作成功,本次'.$row['type_name'].'金额:'.$all['money']]);
            }
        }


        View::assign(['acc_type'=>$this->acc_type,'payment'=>$this->payment,'type'=>$type,'value'=>$value,'memo'=>$all['memo']]);
        return View::fetch('charge_by_admin');
    }


    //充值提现审核
    public function charge_check(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/index/target/admin");
        $all=Request::param();


        if(!empty($all['id'])){

            $id = $all['id'];
            $acc = Db::table('acc_log')->find($id);   

            if(!$acc){
                return json_encode(['code'=>0,'msg'=>'错误！!']);
            }
            if(!$acc['status']==2){
                return json_encode(['code'=>0,'msg'=>'已审核 !!']);
            }

            $customer = Db::table('customer')->find($acc['customer_id']);

            //提现余额检测
            if($acc['type']==7){
                $money = $customer['money'];
                if($money<abs($acc['money'])){
                    return json_encode(['code'=>0,'msg'=>'余额【'.$money."】不足,提现【".abs($acc['money'])."】失败！"]);
                }
                $new_money = $money-abs($acc['money']);
                if($new_money<=0) $new_money=0;
            }

            $acc['status'] = $all['status'];
            $acc['check_by'] = $uid;
            $acc['check_time']=date('Y-m-d H:i:s');

            $res = Db::table('acc_log')->update($acc); 

            //学员第一次缴费时间，用来生产返费计划
            $comm_msg='';
            if($acc['type']==1){
                $res= Db::execute('update customer set fee_time=? where id=?',[date('Y-m-d H:i:s'),$acc['customer_id']]);
                if($res){
                    //返费计划****已不用了，改用领红包的方式。
                    $customer['fee_time'] =date('Y-m-d H:i:s');
                    // $rplan =$this->refund_plan($customer); //halt($rplan);
                    // if($rplan['code']){
                    //     $res =Db::table('refund_plan')->insertAll($rplan['data']);
                    // }

                    //计算推广佣金
                    $comm_for_inviter = $this->comm_for_inviter($customer);
                    $comm_msg = $comm_for_inviter['msg'];
                }
            }


            //提现更新余额
            if($acc['type']==7){
                $res= Db::execute('update customer set money=? where id=?',[$new_money,$acc['customer_id']]);
            }

            if($res){
                return json_encode(['code'=>1,'msg'=>$all['status']==2 ?'审核完成！'.$comm_msg:'款项已取消！'.$comm_msg]);

            }
            return json_encode(['code'=>0,'msg'=>'审核失败，请联系技术人员！']);

        }

        $name = (!empty($all['name']))?$all['name']:'';
        $mobile = (!empty($all['mobile']))?$all['mobile']:'';

        $acc_list = Db::table('acc_log')->where('status','1')->order('create_time','desc')->paginate()->toArray();

        foreach($acc_list['data'] as &$acc){
            $acc['customer_id_name'] = Db::table('customer')->where('id',$acc['customer_id'])->value('name');
            $acc['type_name'] = $this->acc_type[$acc['type']];
            $acc['payment_name'] = $this->payment[$acc['payment']];
            $acc['status_name'] = $this->status[$acc['status']];
            $acc['creater_name'] = $this->users[$acc['creater']]['name'];

        }

        View::assign(['list'=>$acc_list,'name'=>$name,'mobile'=>$mobile]);
        return View::fetch("charge_check");

    }

    //推广佣金产生方法：学员缴费即可生效。
    public function comm_for_inviter($customer){
        //如果没有邀请人就退出
        $inviter_id = $customer['inviter'];
        if(!$inviter_id) return ['code'=>1,'msg'=>'此学员没有邀请人!'];
        
        $inviter = Db::table('customer')->find($inviter_id);
        if(!$inviter) return ['code'=>1,'msg'=>'邀请人无效!'];

        $rc = Db::table('refund_config')->find(1);

        $money=0;
        //推广费：C照和DEF不一样
        if($customer['fee_id']<3){
            $money = $rc['comm_invite'];
        }else{
            $money = $rc['comm_invite2'];
        }
        if(!$money) return ['code'=>1,'msg'=>'未设置推广红包！'];

        $acc_list = Db::query("select count(id) as cnt from acc_log where customer_id=".$inviter['id']." and type=5 and memo like '%,No:".$customer['id']."%'");

        if($acc_list[0]['cnt']>0){
            return ['code'=>1,'msg'=>'推广红包已入过账！'];
        }
   
        //更新邀请人余额,生成一笔账单，不需要审核
        $acc_log=array(
            'type'=>5,
            'customer_id'=>$inviter['id'],
            'dept_id'=>$inviter['dept_id'],
            'money'=>$money,
            'memo'=>'推广红包,No:'.$customer['id']."，学员:【".$customer['name']."】缴学费。",
            'payment'=>'balance',
            'creater'=>2,
            'create_time'=>date('Y-m-d H:i:s'),
            'check_by'=>2, //系统自动审核
            'check_time'=>date('Y-m-d H:i:s'),
            'status'=>2
        );
        $res1 = Db::table('acc_log')->insert($acc_log);
        
        $n_money = $inviter['money']+$money;
        $money_v = md5($customer['create_time'].$n_money);

        if($res1) {
            $res2 = Db::execute('update customer set money=?,money_v=? where id=?',[$n_money,$money_v,$inviter['id']]);
        }

        return ['code'=>1,'msg'=>'学员状态已更新,邀请人余额已入账'.$money];

    }


    //refund_plan 
    //
    public function refund_plan($customer){
        
        $uid=Session::get('logonid');
        $type=$customer['type'];
        if(!$customer || !$type) return ['code'=>0,'msg'=>'error!'];

        //$type=客户类型
        if($type!=12 && $type!=24 && $type!=36 && $type!=48){
            return ['code'=>0,'msg'=>'学员类型不正确!'];
        }

        if(!$customer['fee_id']>2){
            return ['code'=>0,'msg'=>'只有C1,C2学员才有红包计划!'];
        }

        $plan=[];
        for($i=1;$i<=$type;$i++){

            $t = strtotime($customer['fee_time']);
            $t2= strtotime("+".$i." months",$t);
            $plan_time=date('Y-m-d',$t2);

            $plan[]=array(
                'customer_id'=>$customer['id'],
                'money'=>100,
                'memo'=>'红包【'.$i."】",
                'creater'=>2,
                'create_time'=>date('Y-m-d H:i:s',time()),
                'plan_time'=>$plan_time,
                'status'=>1,
                'img'=>'/upload/bao.png'

            );

        }

        //$res = Db::table('refund_plan')->insert($plan);

        return ['code'=>1,'data'=>$plan];

    }


    //客户充值提现
    public function charge($value=''){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/customer_login");

        $all=Request::param();

        $customer = Db::table('customer')->find($uid);
        if(!$customer) return json_encode(['code'=>0,'msg'=>'Customer not found!']);


        if(empty($all['type'])) {
            json_encode(['code'=>0,'msg'=>'Invalid charge type!']);
        }  
        $type=$all['type'];
        $type_name = $this->acc_type[$type];

        //提交充值操作
        if(!empty($all['money_charge'])){
            if(!is_numeric($all['money_charge'])){
                return json_encode(['code'=>0,'msg'=>'Invalid charge value!']);
            }
            if(empty($type)) {
                return json_encode(['code'=>0,'msg'=>'Invalid operation type!']);
            }

            $money = $all['money_charge'];
            //退款或提现
            if($type==2 || $type==4){
                $money = -$all['money_charge'];

            }

            $acc_log=array(
                'type'=>$type,
                'customer_id'=>$uid,
                'money'=>$money,
                'memo'=>$all['memo']?:'',
                'creater'=>2,
                'status'=>1,
                'create_time'=>date('Y-m-d H:i:s')
            );

            if($type==4 && $customer['money']<$all['money_charge']){
                return json_encode(['code'=>0,'msg'=>'余额不够 '.$acc_log['money'].',操作取消！']);
            }

            //Db::execute('update customer set money=money+? where id=?',[$money,$uid]);
            $res =Db::table('acc_log')->insert($acc_log);
            if($res){
                return json_encode(['code'=>1,'msg'=>$type_name.'已提交，请耐心等待审核！']);
            }

            return json_encode(['code'=>0,'msg'=>'Unknow error!']);
        }

        $customer['level_name']=$this->levels[$customer['level']];
        $customer['money']=number_format($customer['money'],2);

        View::assign(['data'=>$customer,'type'=>$type,'type_name'=>$type_name]);
        return View::fetch('charge');
    }

    //账单查询——后台用
    public function acc_log(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login/customer_login");

        $all=Request::param();

        if(!empty($all['cid'])){
          $cid =$all['cid'];
        }

        $view = 'acc_log';
        if(!empty($all['view'])) {
            $cid=$uid;
            $view.="_mobile"; 
        }
        $sdate= !empty($all['sdate'])?$all['sdate']:date('Y-m-d',time()-24*30*3600);
        
        $list=Db::table('acc_log');
        if(!empty($cid)) {
            $list =$list->where('customer_id',$cid);
        }

        //处理查询条件
        $list =$list->where('status',2)->order('create_time','desc')->where('create_time','>',$sdate);
        $list = $list->paginate(30)->toArray();

        foreach($list['data'] as &$log){
            $log['type_name']=$this->acc_type[$log['type']];
            $log['check_id_name']=Db::table('user')->where('id',$log['check_id'])->value('name');
            $log['money'] = number_format($log['money'],2);
            $log['customer_id_name'] = Db::table('customer')->where('id',$log['customer_id'])->value('name');

        }

        $cid = !empty($all['cid'])?$all['cid']:'';
        View::assign(['list'=>$list,'cid'=>$cid]);
        return View::fetch($view);

    }


    //我的收益，app用
    public function my_income(){
        $all=Request::param(); 
        if(empty($all['token'])) return json(['code'=>0,'msg'=>'请登录！']);
        $token =new token();
        $res = $token->check_token($all['token']);
        if($res['code']==0) return json($res);
        $me = $res['customer'];


        $s = Db::query("select type,count(id) as cnt from acc_log where customer_id=? and type in(4,5,6,7) and status=2 group by type;",[$me['id']]);
        $hb=$tg=$dd=$txbs=0;
        foreach($s as $row){
            if($row['type']==4){
                $hb=$row['cnt'];continue;
            }
            if($row['type']==5){
                $tg=$row['cnt'];continue;
            }
            if($row['type']==6){
                $dd=$row['cnt'];continue;
            }
            if($row['type']==7){
                $txbs=$row['cnt'];continue;
            }            
        }

        //已提现
        $tx = Db::query("select sum(money) as tx_money from acc_log where customer_id=? and type=7 and status=2",[$me['id']]);        
        $tx_money=$tx[0]['tx_money'];

        return json(['ye'=>$me['money'],'tg'=>$tg,'dd'=>$dd,'hb'=>$hb,'ytx_bs'=>$txbs,'ytx'=>$tx_money]);

    }


    //账单记录,app用
    public function fee_log(){
        $uid=Session::get('logonid');
        $all=Request::param(); 

        if(empty($uid) && empty($all['token'])) return header("location:/index.php/login");

        $list=Db::table('acc_log')->where('status','in','1,2,3');

        $cid='';
        $name='';

        if(!empty($all['token'])){
            $token =new token();
            $res = $token->check_token($all['token']);
            if($res['code']==0) return json($res);
            $cid = $res['customer']['id'];
        }

        $sdate = !empty($all['sdate'])?substr($all['sdate']." 00:00:00",0,20):'';
        $edate = !empty($all['edate'])?substr($all['edate']." 00:00:00",0,20):date('Y-m-d 23:59:59',time());
        if($edate<$sdate) return json('日期错误！');

        $type=(!empty($all['type']) && $all['type']>0) ?$all['type']:'1,2,3,4,5,6,7'; 
        $list->where('type','in',$type);

        if(!$cid && !empty($all['name'])){
            $name = trim($all['name']);
            $cid = Db::table('customer')->where('name',$name)->value('id');
        }

        $mobile="";
        if(!$cid && !empty($all['mobile'])){
            $mobile = trim($all['mobile']);
            $cid = Db::table('customer')->where('mobile',$mobile)->value('id');
        }

        $dept_id = !empty($all['dept_id'])?$all['dept_id']:'all';
        if($dept_id!='all'){
            $list->where('dept_id',$all['dept_id']);
        }

        if(!empty($cid)){
            $list->where('customer_id',$cid);
        }

        if(!empty($all['sdate'])){
            $list->where('create_time','>=',trim($sdate));
        }
        if(!empty($all['edate'])){
            $list->where('create_time','<=',trim($edate));
        }

        $sum = number_format($list->sum('money'),2);
        $count = number_format($list->count('id'),2);

        if(!empty($all['token'])){
            //app端请求
            $list =$list->order('create_time','desc')->select()->toArray();

            foreach($list as &$log){
                $log['type_name']=$this->acc_type[$log['type']];
                $log['money'] = number_format($log['money'],2);
                $log['status_name'] = $this->status[$log['status']];                
            }

            return json(['code'=>1,'data'=>$list]);
        }

        $list =$list->order('create_time','desc')->paginate(30)->toArray();
        foreach($list['data'] as &$log){
            $log['customer_id_name'] = Db::table('customer')->where('id',$log['customer_id'])->value('name');
            $log['type_name']=$this->acc_type[$log['type']];
            $log['creater']=Db::table('user')->where('id',$log['creater'])->value('name');
            $log['check_by_name']=Db::table('user')->where('id',$log['check_by'])->value('name');

            $log['money'] = number_format($log['money'],2);
            $log['payment_name'] = $this->payment[$log['payment']];
            $log['status_name'] = $this->status[$log['status']];
        }

        //驾校资料
        $school = Db::table('dept')->where('status',1)->where('type',2)->select()->toArray();
        
        if($type=='1,2,3,4,5,6,7') $type='all';

        View::assign([
            'list'=>$list,
            'acc_type'=>$this->acc_type,
            'school'=>$school,
            'name'=>$name,
            'mobile'=>$mobile,
            'dept_id'=>$dept_id,
            'type'=>$type,
            'sdate'=>$sdate,
            'edate'=>$edate,
            'count'=>$count,
            'sum'=>$sum]
        );
        return View::fetch('fee_log');

    }  


    //账单记录
    public function fee_bi(){
        $uid=Session::get('logonid');
        if(empty($uid)) return header("location:/index.php/login");

        $all=Request::param(); 
        $sdate = !empty($all['sdate'])?$all['sdate']." 00:00:00":'';
        $edate = !empty($all['edate'])?$all['edate']." 23:59:59":date('Y-m-d 23:59:59',time());
        if($edate<$sdate) return json('日期错误！');
        $sql ="select dept_id,type,sum(money) as money from acc_log where 1 ";

        $dept_id = !empty($all['dept_id'])?$all['dept_id']:'all';
        if($dept_id!='all'){
            $sql .=" and  dept_id=".$all['dept_id'];
        }


        if(!empty($all['sdate'])){
            $sql .= " and create_time>='".trim($sdate)."'";
        }
        if(!empty($all['edate'])){
           $sql .= " and create_time<='".trim($edate)."'";
        }

        $sql.= " group by dept_id,type";

        //halt($sql);
        $list =Db::query($sql);

        //halt($list);

        foreach($list as &$log){
            $log['dept_id_name'] =$this->dept[$log['dept_id']]['name'];
            $log['type_name']=$this->acc_type[$log['type']];
            $log['money'] = round($log['money'],2);
        }

        $school = Db::table('dept')->where('status',1)->where('type',2)->select()->toArray();
        

        View::assign(['list'=>$list,'school'=>$school,'dept_id'=>$dept_id,'sdate'=>$sdate,'edate'=>$edate]);
        return View::fetch('fee_bi');

    }  



}
